<template>
  <div :id="`wft-advanced-trellis-container-${curComp.id}`" :class="['wft-advanced-trellis-container', { 'wft-container-glowing': curComp.config.isEnchase }]" @dblclick.stop="containerDblclick">
    <div v-for="(curRow, rowIndex) in attrs.row" :key="rowIndex" :style="{ height: rowHeight }" class="row">
      <div v-for="(curCol, colIndex) in attrs.col" :key="colIndex" :data-cur-row="curRow" :data-cur-col="curCol" :class="['col', { 'wft-enter-trellis-item-comp': getCurIndexComp(curRow, curCol) }]" :style="{ width: colWidth, 'pointer-events': curComp.config.isEnchase ? 'auto' : 'none', ...getCompStyle(getCurIndexComp(curRow, curCol)), ...trellisBorderStyle }" @mousedown.stop="trellisItemClick(curRow, curCol)">
        <component
          v-if="getCurIndexComp(curRow, curCol)"
          :is="`${getCurIndexComp(curRow, curCol)?.key}Temp`"
          :cur-comp="getCurIndexComp(curRow, curCol)"
          :panel-json="panelJson"
          style="pointer-events: none;"
        />
        <i v-if="getCurIndexComp(curRow, curCol)" @click.stop="delTrellisItem(curRow, curCol)" class="wft-icon-delete" />
      </div>
    </div>
    <!-- 文字提示 -->
    <div class="wft-advanced-container-tip" v-show="!curComp.config.isEnchase && !curComp.children?.length">双击切换状态</div>
  </div>
</template>
<script setup lang='ts'>
import { DragEventEnum, DragKeyEnum } from '@/enums';
import { useMessage } from '@/hooks';
import Bus from '@/utils/bus';
import { useAttrs } from 'generator/hooks'
import { computed, watch } from 'vue';
import { getUuid } from 'wft-utils';

const props = defineProps<{
  panelJson: TPanel
  curComp: TComp
}>()

const emits = defineEmits<{
  (e: 'onActivated', curComp: TComp): void;
  (e: 'compContext', ...args: any[]): void;
}>()

const attrs = useAttrs(props.curComp.attrs)

const trellisBorderStyle = computed(() => {
  const s = <{[k: string]: any}>{}
  const { show, width, type, color } = attrs.value.border
  if(show) {
    s.border = `${width}px ${type} ${color}`
  }
  return s
})

watch([() => attrs.value.row, () => attrs.value.col], () => {
  props.curComp.children = []
}, { deep: true })

const rowHeight = computed(() => {
  if(attrs.value.row < 1) {
    return '100%'
  }
  return (100 / attrs.value.row) + '%'
})

const colWidth = computed(() => {
  if(attrs.value.col < 1) {
    return '100%'
  }
  return (100 / attrs.value.col) + '%'
})

// 双击可以拖动进来
function containerDblclick() {
  props.curComp.config.isEnchase = !props.curComp.config.isEnchase
  props.curComp.config.draggable = !props.curComp.config.isEnchase
  props.curComp.config.resizable = !props.curComp.config.isEnchase
  if(props.curComp.config.isEnchase) {
    startEvent()
  } else {
    clearEvent()
  }
}

// 监听事件
function startEvent() {
  const advancedContainer = document.getElementById(`wft-advanced-trellis-container-${props.curComp.id}`)!
  advancedContainer.addEventListener(DragEventEnum.ON_DRAG_OVER, compDragover)
  advancedContainer.addEventListener(DragEventEnum.ON_DROP, compDrop)
  advancedContainer.addEventListener(DragEventEnum.ON_DRAG_ENTER, compDragEnter)
  advancedContainer.addEventListener(DragEventEnum.ON_DRAG_LEAVE, compDragLeave)
}

// 清除事件
function clearEvent() {
  const advancedContainer = document.getElementById(`wft-advanced-trellis-container-${props.curComp.id}`)!
  advancedContainer.removeEventListener(DragEventEnum.ON_DRAG_OVER, compDragover)
  advancedContainer.removeEventListener(DragEventEnum.ON_DROP, compDrop)
  advancedContainer.removeEventListener(DragEventEnum.ON_DRAG_ENTER, compDragEnter)
  advancedContainer.removeEventListener(DragEventEnum.ON_DRAG_LEAVE, compDragLeave)
}

function compDragover(e: DragEvent) {
  e.preventDefault()
}

// 拖入目标容器
function compDragEnter(event: DragEvent) {
  const targetDom = <HTMLElement>event.target
  targetDom?.classList.add('drag-enter-active')
}

// 离开目标容器
function compDragLeave(event: DragEvent) {
  const targetDom = <HTMLElement>event.target
  targetDom?.classList.remove('drag-enter-active')
}

// 松开拖拽控件
function compDrop(event: DragEvent) {
  if(!event.dataTransfer?.getData(DragKeyEnum.DRAG_DATA_KEY)) return
  const dragData = JSON.parse(event.dataTransfer.getData(DragKeyEnum.DRAG_DATA_KEY))
  const targetDom = <HTMLElement>event.target
  if(dragData.curCom.type == 'advanced') {
    targetDom?.classList.remove('drag-enter-active')
    return useMessage().warning('容器中不可再嵌套高级控件！')
  }
  if(dragData.curCom.type == 'inertia') {
    targetDom?.classList.remove('drag-enter-active')
    return useMessage().warning('容器中不可嵌套惰性控件！')
  }
  const curCom = JSON.parse(JSON.stringify(dragData.curCom)) as TComp
  curCom.id = getUuid()
  curCom.config.isActive = true
  curCom.parentId = props.curComp.id
  curCom.parentKey = props.curComp.key
  const curRow = Number(targetDom.dataset.curRow)
  const curCol = Number(targetDom.dataset.curCol)
  curCom.style.coors = { row: curRow, col: curCol }
  const curChildIndex = props.curComp.children!.findIndex(item => item?.style.coors!.row == curRow && item?.style.coors!.col == curCol)
  if(curChildIndex >= 0) {
    props.curComp.children?.splice(curChildIndex, 1)
  }
  props.curComp.children?.forEach(item => item.config.isActive = false)
  props.curComp.children!.push(curCom)
  emits('onActivated', curCom)
  Bus.emit('addStack')
  Bus.emit('startEventKeydown')
  targetDom?.classList.remove('drag-enter-active')
  if(event.dataTransfer?.getData(DragKeyEnum.DRAG_DATA_KEY)) {
    event.dataTransfer.clearData(DragKeyEnum.DRAG_DATA_KEY)
  }
}

// 点击内部控件
function trellisItemClick(curRow: number, curCol: number) {
  const curComp = getCurIndexComp(curRow, curCol)
  if(curComp) {
    props.curComp.children!.forEach(item => {
      if(!item) return
      item.config.isActive = false
    })
    curComp.config.isActive = true
    emits('onActivated', curComp)
  }
}

// 移除控件
function delTrellisItem(curRow: number, curCol: number) {
  const index = props.curComp.children!.findIndex(item => item?.style.coors!.row == curRow && item?.style.coors!.col == curCol)
  if(index >= 0) {
    props.curComp.children?.splice(index, 1)
  }
}

// 获取当前位置的控件数据
function getCurIndexComp(curRow: number, curCol: number) {
  return props.curComp.children?.find(item => item.style.coors!.row == curRow && item.style.coors!.col == curCol)
}

// 内部控件的样式 去掉边框以宫格边框为主
function getCompStyle(comp: TComp | undefined) {
  if(!comp) return {}
  const s = <{[k: string]: any}>{}
  const { background } = comp.style
  s.backgroundColor = background.color || 'transparent'
  s.backgroundImage = `url(${background.img})`
  s.backgroundSize = background.size
  s.backgroundRepeat = background.repeat
  s.backgroundPosition = background.position
  return s
}

</script>
<style scoped>
.wft-advanced-trellis-container {
  width: 100%;
  height: 100%;
}

.wft-advanced-trellis-container > .row {
  width: 100%;
  display: flex;
}

.wft-advanced-trellis-container > .row > .col {
  height: 100%;
  /* border-bottom: 1px dashed #086d6d;
  border-right: 1px dashed #086d6d; */
  box-sizing: border-box;
  position: relative;
}

.wft-advanced-trellis-container > .row > .col > .wft-icon-delete {
  position: absolute;
  font-size: 14px;
  bottom: 5px;
  right: 5px;
  z-index: 999;
}

.wft-advanced-container-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 14px;
  color: #999;
}

.wft-container-glowing {
  box-shadow: 0 0 0 #d3e3fd, 0 0 10px #d3e3fd, 0 0 10px #d3e3fd, 0 0 30px #d3e3fd;
  cursor: auto;
}

.drag-enter-active {
  background-color: rgba(160, 197, 232, .6)!important;
}

.wft-enter-trellis-item-comp:hover {
  background-color: rgba(160, 197, 232, .6)!important;
  cursor: pointer;
}
</style>